package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.OrderDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Customer;
import edu.ynu.se.xiecheng.achitectureclass.entity.LineItem;
import edu.ynu.se.xiecheng.achitectureclass.entity.Order;
import edu.ynu.se.xiecheng.achitectureclass.entity.ShopItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.NoSuchElementException;
import java.util.Optional;

@Service
public class OrderService extends LogicService<OrderDao, Order,Long> {
    public OrderService(@Qualifier("orderDao") @Autowired OrderDao dao) {
        super(dao);
    }
    @Autowired
    private OrderDao orderDao;

    public Order createOrder(Customer customer) {
        Order order = new Order();
        order.setCustomer(customer);

        orderDao.save(order);

        return order;
    }

    public LineItem addLineItem(Order order, ShopItem shopItem) {
        LineItem lineItem = new LineItem();
        lineItem.setOrder(order);
        lineItem.setShopItem(shopItem);

        // 其他操作，如设置数量、计算金额等

        order.getLineItems().add(lineItem); // 添加到订单的商品明细列表中

        return lineItem;
    }

    public void payOrder(Long orderId) {
        Optional<Order> optionalOrder = orderDao.findById(orderId);
        if (optionalOrder.isPresent()) {
            Order order = optionalOrder.get();
            order.payOrder();
            orderDao.save(order);
        } else {
            throw new NoSuchElementException("Order not found");
        }
    }
}
